<template>
    <div class="fgqefr23f3">
        <div>
            <!-- 多语言开关 -->
            <h4 style="margin-left: 50px;">多语言设置</h4>
            <div class="form-item">
                <label for="multilingual" class="form-label">多语言开关</label>
                <el-switch id="multilingual" class="mdwind" v-model="formlang.multilingual" active-value="1"
                    inactive-value="0" @change="toggleMultilingual"></el-switch>
                <el-button type="success" size="small" :disabled="isDisabled" @click="chouti111">语言设置</el-button>
            </div>

        </div>
        <div>
            <!-- 更新缓存 -->
            <h4 style="margin-left: 50px;margin-top: 50px;">缓存设置</h4>
            <div class="form-item">
                <label class="form-label">更新首页缓存</label>
                <div class="gxhc">
                    <el-button type="success" size="small" :loading="indexStorage" @click="updStorage()">点击更新缓存</el-button>
                </div>
            </div>
        </div>
        <div>
            <!-- 更新缓存 -->
            <h4 style="margin-left: 50px;margin-top: 50px;">联系我们</h4>
            <div class="form-item">
                <label class="form-label">联系我们</label>
                <div style="flex: 1;display: flex;">
                    <el-input style="flex:2" v-model="contact_us" :disabled="contact_us_type == '1'"></el-input>
                    <el-button style="flex: 1;margin-left: 10px;" type="primary" size="small" @click="editus()">{{
                        contact_us_type == '0' ? '确定' : '点击编辑'
                    }}</el-button>
                </div>
            </div>
        </div>
        <div>
            <!-- 爬虫 stock 条目设置 -->
            <h4 style="margin-left: 50px;margin-top: 50px;">展示条目设置</h4>
            <div class="form-item">
                <label for="crawlerStock" class="form-label">爬虫 stock 条目设置</label>
                <el-select id="crawlerStock" v-model="form.crawlerStock"
                    @change="updateSetting('crawler_stock_number_settings')">
                    <el-option v-for="number in numbers" :key="number" :label="number" :value="number"></el-option>
                </el-select>
            </div>

            <!-- 文章页面设置展示数量 -->
            <div class="form-item">
                <label for="articleNumber" class="form-label">文章页面设置展示数量</label>
                <el-select id="articleNumber" v-model="form.articleNumber" @change="updateSetting('number_of_articles')">
                    <el-option v-for="number in numbers" :key="number" :label="number" :value="number"></el-option>
                </el-select>
            </div>

            <!-- 选股 recent adjustment 数量 -->
            <div class="form-item">
                <label for="recentAdjustment" class="form-label">选股 recent adjustment 数量</label>
                <el-select id="recentAdjustment" v-model="form.recentAdjustment"
                    @change="updateSetting('recent_adjustment')">
                    <el-option v-for="number in numbers" :key="number" :label="number" :value="number"></el-option>
                </el-select>
            </div>
            <!-- 首页新闻展示数量设置 -->
            <div class="form-item">
                <label for="index_news_number" class="form-label">首页新闻展示数量设置</label>
                <el-select id="index_news_number" v-model="form.index_news_number"
                    @change="updateSetting('index_news_number')">
                    <el-option v-for="number in numbers" :key="number" :label="number" :value="number"></el-option>
                </el-select>
            </div>
            <!-- 首页文章展示数量设置 -->
            <div class="form-item">
                <label for="index_articles_number" class="form-label">首页文章展示数量设置</label>
                <el-select id="index_articles_number" v-model="form.index_articles_number"
                    @change="updateSetting('index_articles_number')">
                    <el-option v-for="number in numbers" :key="number" :label="number" :value="number"></el-option>
                </el-select>
            </div>
        </div>
        <el-drawer title="语言设置" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
            <div v-loading="loadingchouti">
                <h3 style="text-align: center;">语言启用/禁用</h3>
                <div class="form-item">
                    <label for="multilingual" class="form-label">英语</label>
                    <el-switch @change="Languageswitch('en')" v-model="langlist.en" active-value="1"
                        inactive-value="0"></el-switch>
                </div>
                <div class="form-item">
                    <label for="multilingual" class="form-label">繁体中文</label>
                    <el-switch @change="Languageswitch('tw')" v-model="langlist.zh_tw" active-value="1"
                        inactive-value="0"></el-switch>
                </div>
                <div class="form-item">
                    <label for="multilingual" class="form-label">简体中文</label>
                    <el-switch @change="Languageswitch('cn')" v-model="langlist.zh_cn" active-value="1"
                        inactive-value="0"></el-switch>
                </div>

                <div class="form-item">
                    <label for="multilingual" class="form-label">日语</label>
                    <el-switch @change="Languageswitch('ja')" v-model="langlist.ja" active-value="1"
                        inactive-value="0"></el-switch>
                </div>

                <div class="form-item">
                    <label for="multilingual" class="form-label">韩语</label>
                    <el-switch @change="Languageswitch('ko')" v-model="langlist.ko" active-value="1"
                        inactive-value="0"></el-switch>
                </div>
                <h3 style="text-align: center;margin-top: 35px;">设置默认语言</h3>
                <div class="form-item">
                    <label class="form-label">默认语言</label>
                    <el-select v-model="default_lang" @change="default_langSet()">
                        <el-option v-if="langlist.en == 1" label="英语" value="en"></el-option>
                        <el-option v-if="langlist.zh_tw == 1" label="繁体中文" value="zh_tw"></el-option>
                        <el-option v-if="langlist.zh_cn == 1" label="简体中文" value="zh_cn"></el-option>
                        <el-option v-if="langlist.ja == 1" label="日语" value="ja"></el-option>
                        <el-option v-if="langlist.ko == 1" label="韩语" value="ko"></el-option>
                    </el-select>
                </div>
            </div>
        </el-drawer>
    </div>
</template>
  
<script>
import { numberOfSystemEntries, setMultilingualOnOff, getEntry, updateCache, getLanguageList, editLanguage, setDefaultLanguage } from "@/utils/api";
export default {
    name: 'setupPage',
    computed: {
        isDisabled() {

            return this.formlang.multilingual == '1' ? false : true
        }
    },
    data() {
        return {
            loadingchouti: true,
            drawer: false,
            direction: 'rtl',
            // 下拉框数据
            numbers: Array.from({ length: 99 }, (_, i) => i + 1), // 1 到 99 的数组
            // 表单数据
            form: {
                crawlerStock: null,
                articleNumber: null,
                recentAdjustment: null,
                index_news_number: null,
                index_articles_number: null,
            },
            default_lang: '',
            formlang: {
                multilingual: "0", // 初始化状态，默认为关闭（0）
            },
            indexStorage: false,
            contact_us: '',
            contact_us_type: '1',
            langlist: {
                zh_cn: '0',
                zh_tw: '0',
                ja: '0',
                ko: '0',
                en: '0'
            },
        };
    },
    mounted() {
        this.getNum();
        this.getlanglist()
    },
    methods: {
        async default_langSet() {
            this.loadingchouti = true
            let data = {}
            data.default_language = this.default_lang


            const res = await setDefaultLanguage(data).catch((err) => {
                console.error(err);
                this.$message.error("接口调用失败，请稍后重试！");
                return null;
            });

            if (res && res.status == "200") {
                this.$message.success(res.data.message);
                this.updStorage()
                setTimeout(() => {
                    this.getNum()
                    this.loadingchouti = false
                }, 1000);

            } else {
                this.$message.error(res.data.message);
            }
        },
        chouti111() {
            this.drawer = true
            this.getlanglist()
        },
        handleClose(done) {
            done();
            this.loadingchouti = true
        },
        editus() {
            if (this.contact_us_type === '0') {
                this.set_contact_us();
            }
            this.contact_us_type = this.contact_us_type === '0' ? '1' : '0';
        },
        async set_contact_us() {
            const data = {
                "key": "contact_us",
                "value": this.contact_us
            };

            const res = await numberOfSystemEntries(data).catch((err) => {
                console.error(err);
                return null;
            });

            if (res && res.status == "200") {
                this.$message.success(res.data.message);
                this.updStorage()
                this.getNum()

            } else {
                this.$message.error(res.data.message);
            }
        },
        async updateSetting(key) {
            // 获取对应字段的 key 值
            let field = '';

            // 使用 if-else 或 switch 来替代三元运算符
            if (key === "crawler_stock_number_settings") {
                field = "crawlerStock";
            } else if (key === "number_of_articles") {
                field = "articleNumber";
            } else if (key === "recent_adjustment") {
                field = "recentAdjustment";
            } else if (key === "index_news_number") {
                field = "index_news_number";
            } else if (key === "index_articles_number") {
                field = "index_articles_number";
            }

            // 保存更改前的值
            const previousValue = this.form[field];

            // 更新当前的值
            const value = this.form[field];

            const data = { key, value };

            const res = await numberOfSystemEntries(data).catch((err) => {
                console.error(err);
                this.$message.error(err.response.data.message);

                // 强制还原下拉框状态
                this.$set(this.form, field, previousValue);
                return null;
            });

            if (res && res.status == "200") {
                this.$message.success(res.data.message);
            } else {
                if (res) {
                    this.$message.error(res.data.message || "未知错误");
                }

                // 强制还原下拉框状态
                this.$set(this.form, field, previousValue);
            }
        },
        async toggleMultilingual(value) {
            const previousValue = this.formlang.multilingual; // 保存切换前的状态
            const data = { multilingual: value };

            const res = await setMultilingualOnOff(data).catch((err) => {
                console.error(err);
                this.$message.error("接口调用失败，请稍后重试！");
                // 还原开关状态
                this.formlang.multilingual = previousValue;
                return null;
            });

            if (res && res.status == "200") {
                this.$message.success(res.data.message);
                this.updStorage()
            } else {
                if (res) {
                    this.$message.error(res.data.message || "未知错误");
                }
                // 还原开关状态
                this.formlang.multilingual = previousValue;
            }
        },
        async getNum() {
            const res = await getEntry().catch((err) => {
                console.error(err);
                this.$message.error("接口调用失败，请稍后重试！");
                return null;
            });

            if (res && res.status == "200") {
                // this.$message.success(res.data.message);
                this.form.crawlerStock = res.data.data.crawler_stock_number_settings;
                this.form.articleNumber = res.data.data.number_of_articles;
                this.form.recentAdjustment = res.data.data.recent_adjustment;
                this.form.index_news_number = res.data.data.index_news_number;
                this.form.index_articles_number = res.data.data.index_articles_number;
                this.contact_us = res.data.data.contact_us
                this.formlang.multilingual = res.data.data.multilingual;
                this.default_lang = res.data.data.default_language


            } else {
                this.$message.error(res.data.message);
            }
        },
        async updStorage() {
            this.indexStorage = true
            const res = await updateCache().catch((err) => {
                console.error(err);
                this.$message.error("接口调用失败，请稍后重试！");
                return null;
            });

            if (res && res.status == "200") {
                this.indexStorage = false
            } else {
                this.$message.error(res.data.message);
                this.indexStorage = false
            }
        },
        async getlanglist() {
            const res = await getLanguageList().catch((err) => {
                console.error(err);
                this.$message.error("接口调用失败，请稍后重试！");
                return null;
            });

            if (res && res.status == "200") {
                // this.$message.success(res.data.message);
                this.loadingchouti = false
                this.langlist.en = res.data.data.value.en + ''
                this.langlist.ko = res.data.data.value.ko + ''
                this.langlist.ja = res.data.data.value.ja + ''
                this.langlist.zh_tw = res.data.data.value.zh_tw + ''
                this.langlist.zh_cn = res.data.data.value.zh_cn + ''
            } else {
                this.$message.error(res.data.message);
            }

        },
        async Languageswitch(lang) {

            let data = {}
            if (lang == 'en') data.en = this.langlist.en
            if (lang == 'tw') data.zh_tw = this.langlist.zh_tw
            if (lang == 'cn') data.zh_cn = this.langlist.zh_cn
            if (lang == 'ja') data.ja = this.langlist.ja
            if (lang == 'ko') data.ko = this.langlist.ko


            const res = await editLanguage(data).catch((err) => {
                console.error(err);
                this.$message.error("接口调用失败，请稍后重试！");
                return null;
            });

            if (res && res.status == "200") {
                this.$message.success(res.data.message);
                this.updStorage()

            } else {
                this.$message.error(res.data.message);
            }
        },

    }
}
</script>
  

<style scoped>
.fgqefr23f3 {
    width: 100%;
    display: flex;
    flex-direction: column;
    min-height: 90%;
    padding: 25px;
}

form {
    border: 1px #e8e8e8 solid;
    border-radius: 5px;
    padding: 15px;
    margin: 10px;

}

.gxhc {
    flex: 1;
}

h4 {
    border-bottom: 1px solid #f1f1f1;
}

.form-item {
    display: flex;
    margin: 15px 0;
    width: 80%;

}

.form-label {
    flex: 1;
    margin-right: 25px;
    display: flex;
    align-items: center;
    justify-content: right;
    font-size: 14px;
}

.el-select {
    flex: 1;
}

.el-switch {
    flex: 1;
}

.mdwind {
    height: 32px;
}
</style>